package com.neuedu.ylbx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.ylbx.mapper.SysUserMapper;
import com.neuedu.ylbx.pojo.SysUser;
import com.neuedu.ylbx.service.AuthService;
import com.neuedu.ylbx.utils.ResultVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

@Service
public class AuthServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements AuthService {

    public ResultVo<SysUser> login(String username, String password)throws Exception{
        QueryWrapper qw=new QueryWrapper();
        qw.eq("username",username);
        qw.eq("password",password);
        SysUser sysuser=getOne(qw);
        System.out.println(sysuser);
        if(sysuser!=null){
            if(sysuser.getDeleted()==0){
                HashMap<String,Object> map=new HashMap<>();
                //如果登录验证成功，则需要生成令牌token（token就是按照特定规则生成的字符串）
                JwtBuilder builder = Jwts.builder();
                String token = builder.setSubject(username) //主题，就是token中携带的数据
                        .setIssuedAt(new Date()) //设置token的生成时间
                        .setId(sysuser.getId().toString()) //设置用户id为token id
                        .setClaims(map)  //map中可以存放用户的⻆色权限信息
                        .setExpiration(new Date(System.currentTimeMillis() +   24 * 60 * 60 * 1000))//设置过期时间
                        .signWith(SignatureAlgorithm.HS256,"neuedu123456")//设置加密方式和加密密码
                        .compact();
                return ResultVo.ok(sysuser,token);
            }
            return ResultVo.fail("无权限，请联系管理员");
        }
        return ResultVo.fail("账号密码错误");
    }
}
